import { Controller } from 'egg';

export default class BindPhoneController extends Controller {
    public async sendSms() {
        const { ctx, service } = this;
        ctx.validate({
            phone: {
                type: 'string',
                allowEmpty: false,
            },
        });
        const phone = ctx.request.body.phone;
        const smsCode = ctx.helper.generateSmsCode();
        const token = ctx.helper.generateToken();
        // 临时保存用户短信验证码
        const saveSmsCachePromise = service.cache.saveSmsCache(token, {
            phone,
            sms_code: smsCode,
        });
        // 发送短信验证码
        const sendSmsCodePromise = service.sms.sendSmsCode(phone, smsCode);
        await Promise.all([saveSmsCachePromise, sendSmsCodePromise]);
        return ctx.helper.success(this.ctx, {token}); // 返回请求成功
    }

    public async bindPhone() {
        const { ctx, service } = this;
        ctx.validate({
            sms_token: {
                type: 'string',
                allowEmpty: false,
            },
            sms_code: {
                type: 'string',
                allowEmpty: false,
                format: /\d{6}/,
            },
            username: 'string',
            code: 'string',
        });
        const { sms_token, sms_code, username, code } = ctx.request.body;
        const smsCache = await service.cache.getSmsCache(sms_token);
        await service.cache.delSmsCache(sms_token);
        if (!smsCache || sms_code !== smsCache.sms_code || !smsCache.phone) {
            return this.ctx.helper.smsCodeError();
        }

        const openid = await this.service.weixin.getOpenid(code);
        if (!openid) {
            this.ctx.helper.innerError('微信登录过期');
        }

        await service.bindPhone.bindPhone(openid, username, smsCache.phone);
        const result = await service.login.loginByOpenID(openid);
        return this.ctx.helper.success(this.ctx, result);
    }
}
